<template>
    <div class="mod-dict">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
            <el-form-item>
                <el-input v-model="dataForm.label" :placeholder="$t('dicManage.labelName')" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="dataForm.type" :placeholder="$t('dicManage.type')" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="getDataList()">{{ $t('handle.search') }}</el-button>
                <el-button v-if="isAuth('ic:dict:save')" type="primary" @click="addOrUpdateHandle()">{{ $t('handle.add') }}</el-button>
                <!-- <el-button type="primary" @click="handleExport()">导出</el-button> -->
                <!-- <el-button type="primary" @click="handleImport()">导入</el-button> -->
                <el-button v-if="isAuth('batch:delete')" type="danger"  @click="deleteHandle()" :disabled="dataListSelections.length <= 0">{{ $t('handle.batchDelete') }} </el-button>
            </el-form-item>
            </el-form>
        <el-table
            :data="dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%;">
            <el-table-column
                type="selection"
                header-align="center"
                align="center"
                width="50">
            </el-table-column>
            <el-table-column
                v-if='show'
                prop="id"
                header-align="center"
                align="center"
                width="80"
                label="ID">
            </el-table-column>
            <el-table-column
                type="index"
               :label="$t('tabble.No')"
                width="50"
                :index="indexMethod">
            </el-table-column>
            <el-table-column
                prop="label"
                header-align="center"
                align="center"
                :label="$t('dicManage.labelName')">
            </el-table-column>
            <el-table-column
                prop="value"
                header-align="center"
                align="center"
                :label="$t('dicManage.dataValue')">
            </el-table-column>
            <el-table-column
                prop="type"
                header-align="center"
                align="center"
                :label="类型">
            </el-table-column>
            <el-table-column
                prop="isSystem"
                header-align="center"
                align="center"
                :label="$t('dicManage.isSystemDic')">
                <template slot-scope="scope">
                <el-tag v-if="scope.row.isSystem === 1" size="small" type="danger">{{ $t('status.yes') }}</el-tag>
                <el-tag v-else size="small">{{ $t('status.no') }}</el-tag>
                </template>
            </el-table-column>
             <el-table-column
                prop="status"
                header-align="center"
                align="center"
                :label="$t('status.status')">
                <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 2" size="small" type="danger">{{ $t('status.disabled') }}</el-tag>
                <el-tag v-else size="small">{{ $t('status.enable') }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="description"
                header-align="center"
                align="center"
               :label="$t('dicManage.describe')">
            </el-table-column>
            <el-table-column
                prop="sort"
                header-align="center"
                align="center"
                :label="$t('tabble.sort')">
            </el-table-column>
            <el-table-column
                fixed="right"
                header-align="center"
                align="center"
                width="150"
                :label="$t('handle.handle')">
                <template slot-scope="scope">
                <el-button v-if="isAuth('ic:dict:update')" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ $t('handle.update') }} </el-button>
                <el-button v-if="isAuth('ic:dict:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)">{{ $t('handle.delete') }} </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
        <!-- 弹窗, 新增 / 修改-->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <el-dialog :visible.sync="importExcelVisible" v-if="importExcelVisible">
       <el-row :gutter="24">
        <el-col :span="12">
            <p >1. 请先下载并填写【导入模板】</p>
            <el-button size="large" type="warning" @click="handleTemplate">导入模板</el-button>
        </el-col>
        <el-col :span="12">
          <p >2. 点击【选择文件】,确定无误后,再点击上传</p>
         <el-upload :before-upload="handleExcel" action="">
            <el-button type="primary">选择文件</el-button>
         </el-upload>
         <div v-if="excel !== null">文件名: {{ excel.name }} <el-button type="primary" @click="handleExcelUpload" :loading="excelLoading">{{ excelLoading ? '上传中...' : '请点击上传' }}</el-button></div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import AddOrUpdate from "./dict-add-or-update";
import { isAuth } from "@/utils";
export default {
  data() {
    return {
      dataForm: {
        label: "",
        type: ""
      },
      excel: null,
      excelLoading: false,
      importExcelVisible: false,
      show: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    };
  },
  // 引入的组件
  components: {
    AddOrUpdate
  },
  // 一进页面就加载
  activated() {
    this.getDataList();
  },
  methods: {
    /******************excel相关***********************/
    // 导出
    handleExport() {
      this.$http({
        url: "/dg-ic/ic/dict/export",
        method: "post",
        data: this.$http.adornData({
          // 后续参数
          label: this.dataForm.label
        }),
        responseType: "blob"
      }).then(res => {
        console.log(res)
        const link = document.createElement("a");
        let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        var time = new Date();
        var currTime = time.toLocaleString();
        link.setAttribute("download", "字典_" + currTime + ".xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },
    // 导入
    handleImport() {
      this.importExcelVisible = true;
    },
    handleExcel(file) {
      this.excel = file;
      return false;
    },
    handleTemplate() {
      this.$http({
        url: "/dg-ic/ic/dict/importTemplate",
        method: "post",
        responseType: "blob"
      }).then(res => {
        console.log(res)
        const link = document.createElement("a");
        let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", "导入模板.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },
    /**上传excel */
    handleExcelUpload() {
      this.excelLoading = true;
      const form = new FormData();
      form.append("file", this.excel);
      this.$http({
        url: "/dg-ic/ic/dict/import",
        method: "post",
        data: form
      }).then(res => {
        this.excel = null;
        this.excelLoading = false;
        if (res.data && res.data.code === 0) {
          this.$message({
            message: res.data.msg,
            type: "success",
            duration: 1500,
            onClose: () => {
              this.getDataList();
              this.importExcelVisible = false;
            }
          });
        } else {
           this.$message({
            message: res.data.msg,
            type: "error",
            duration: 1500,
            onClose: () => {
              this.getDataList();
              this.importExcelVisible = false;
            }
          });
        }
      });
    },
    /******************excel相关***********************/
    indexMethod(index) {
      return index + 1;
    },
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: "/dg-ic/ic/dict/list",
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          label: this.dataForm.label,
          type: this.dataForm.type
          // 后续参数
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.data.list;
          this.totalPage = data.data.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增/修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$http({
            url: `dg-ic/ic/dict/delete`,
            method: "delete",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                }
              });
            }
          });
        })
        .catch(() => {});
    }
  }
};
</script>
